package com.bckj.fastboot.iot.data.mongo.repository;

import com.bckj.fastboot.core.extra.mongo.AbstractMongoRepository;
import com.bckj.fastboot.core.extra.mongo.MongoOps;
import com.bckj.fastboot.iot.common.dto.request.MessageRecordRequest;
import com.bckj.fastboot.iot.common.repository.MessageRecordRepository;
import com.bckj.fastboot.iot.data.mongo.convert.MessageRecordConvert;
import com.bckj.fastboot.iot.data.mongo.entity.MessageRecord;
import com.mongodb.client.result.UpdateResult;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

/**
 * MessageRecordRepositoryImpl
 *
 * @author wfc
 **/
@Repository
public class MessageRecordRepositoryImpl
    extends AbstractMongoRepository<MessageRecord, Long>
        implements MessageRecordRepository {

    private final MessageRecordConvert messageRecordConvert;

    public MessageRecordRepositoryImpl(
            MongoOps mongoOps,
            MessageRecordConvert messageRecordConvert
    ) {
        super(mongoOps, MessageRecord.class, "message_record");
        this.messageRecordConvert = messageRecordConvert;
    }

    @Override
    public boolean save(MessageRecordRequest request) {
        var entity = messageRecordConvert.toEntity(request);
        return save(entity);
    }

    @Override
    public boolean updateById(MessageRecordRequest request) {
        MessageRecord entity = messageRecordConvert.toEntity(request);
        return updateById(entity);
    }

    @Override
    public boolean updateByMsgId(MessageRecordRequest request) {
        Query query = Query.query(Criteria.where("msgId").is(request.getMsgId()));
        Update update = new Update();
        update.set("status", request.getStatus());
        UpdateResult result = updateFirst(query, update);
        return result.getModifiedCount() > 0;
    }
}
